/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.update;

import hibernate.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Felipe
 */
public class UpdateController {
    
    private UpdateListener mUpdateListener = null;
    
    public UpdateController() {
        this(null);
    }
    
    public UpdateController(UpdateListener pUpdateListener) {
        mUpdateListener = pUpdateListener;
    }       
    
    public void setUpdateListener(UpdateListener pUpdateListener) {
        mUpdateListener = pUpdateListener;
    }       
    
    public void delete(Object ... object) {
        Session session = null;
        try {
            SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
            session = sessionFactory.openSession();
            session.beginTransaction();  
            for (int i = 0; i < object.length; i++) {
                if (object[i] == null) break;
                session.delete(object[i]);
            }
            session.getTransaction().commit();
            if (mUpdateListener != null)
                mUpdateListener.onUpdateComplete();
        } catch (Exception e) {
            e.printStackTrace();
            if (mUpdateListener != null)
                mUpdateListener.onUpdateError("", e);            
        } finally {
            session.flush();
            session.close();            
        }
    }         
    
    public void update(Object ... object) {
        Session session = null;
        try {
            SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
            session = sessionFactory.openSession();
            session.beginTransaction();  
            for (int i = 0; i < object.length; i++) {
                if (object[i] == null) break;
                session.update(object[i]);
            }
            session.getTransaction().commit();
            if (mUpdateListener != null)
                mUpdateListener.onUpdateComplete();
        } catch (Exception e) {
            e.printStackTrace();
            if (mUpdateListener != null)
                mUpdateListener.onUpdateError("", e);            
        } finally {
            session.flush();
            session.close();            
        }
    }
    
    public interface UpdateListener {
        
        public void onUpdateComplete();
        
        public void onUpdateError(String message, Exception e);      
        
    };
    
}